package com.meiyuetao.myt.chinababy.web.action;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lab.s2jh.core.annotation.MetaData;
import lab.s2jh.core.service.BaseService;
import lab.s2jh.core.service.Validation;
import lab.s2jh.core.web.json.HibernateAwareObjectMapper;
import lab.s2jh.core.web.view.OperationResult;
import lab.s2jh.ctx.DynamicConfigService;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.struts2.rest.HttpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.meiyuetao.myt.chinababy.entity.CbLotteryWin;
import com.meiyuetao.myt.chinababy.entity.CbLotteryWinDetail;
import com.meiyuetao.myt.chinababy.service.CbLotteryAwardService;
import com.meiyuetao.myt.chinababy.service.CbLotteryWinService;
import com.meiyuetao.myt.core.entity.RC4Entity;
import com.meiyuetao.myt.core.web.MytBaseController;
import com.meiyuetao.myt.md.entity.Commodity;
import com.meiyuetao.myt.md.service.CommodityService;

@MetaData("获奖")
public class CbLotteryWinController extends MytBaseController<CbLotteryWin, Long> {
    @Value("${cfg.rc4.key}")
    private String key;

    @Autowired
    private DynamicConfigService dynamicConfigService;
    @Autowired
    private CbLotteryWinService cbLotteryWinService;
    @Autowired
    private CbLotteryAwardService cbLotteryAwardService;
    @Autowired
    private CommodityService commodityService;

    @Override
    protected BaseService<CbLotteryWin, Long> getEntityService() {
        return cbLotteryWinService;
    }

    @Override
    protected void checkEntityAclPermission(CbLotteryWin entity) {
        // TODO Add acl check code logic
    }

    protected void setupDetachedBindingEntity(Long id) {
        bindingEntity = getEntityService().findDetachedOne(id, "cbLotteryWinDetails");
    }

    @MetaData("[TODO方法作用]")
    public HttpHeaders todo() {
        // TODO
        setModel(OperationResult.buildSuccessResult("TODO操作完成"));
        return buildDefaultHttpHeaders();
    }

    @Override
    @MetaData("保存")
    public HttpHeaders doSave() {
        for (CbLotteryWinDetail item : bindingEntity.getCbLotteryWinDetails()) {
            if (item.getCommodity().getSku() != null) {
                Commodity commodity = commodityService.findByBarcode(item.getCommodity().getSku());
                item.setCommodity(commodity);
            }
        }
        return super.doSave();
    }

    @Override
    @MetaData("创建")
    public HttpHeaders doCreate() {
        return super.doCreate();
    }

    @Override
    @MetaData("更新")
    public HttpHeaders doUpdate() {
        return super.doUpdate();
    }

    @Override
    @MetaData("删除")
    public HttpHeaders doDelete() {
        return super.doDelete();
    }

    @Override
    @MetaData("查询")
    public HttpHeaders findByPage() {
        return super.findByPage();
    }

    @SuppressWarnings({ "unchecked", "static-access" })
    @MetaData("获奖生成定单")
    public HttpHeaders biuldOrder() {
        int i = 0;
        String failMsg = "";
        if (StringUtils.isNotBlank(getParameter("ids"))) {
            Long[] ids = this.getSelectSids();
            Validation.isTrue(ids != null && ids.length > 0, "至少选择一条记录");
            List<CbLotteryWin> cbLotteryWins = cbLotteryWinService.findAll(ids);
            for (CbLotteryWin item : cbLotteryWins) {
                if (item.getBoxOrder() == null) {
                    RC4Entity rc4Entity = new RC4Entity();
                    String prizeparams = rc4Entity.encry_RC4_string("{customer_id:'" + item.getCustomerProfile().getId() + "',award_type:'" + item.getAwardType().name() + "'}",
                            getKey());
                    HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
                    CloseableHttpClient client = httpClientBuilder.build();
                    HttpPost httpPost = new HttpPost(dynamicConfigService.getString("cfg.api.prizes.orders.url"));
                    List<NameValuePair> formparams = new ArrayList<NameValuePair>();
                    formparams.add(new BasicNameValuePair("prizeparams", prizeparams));
                    String response = null;
                    try {
                        UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
                        httpPost.setEntity(urlEncodedFormEntity);
                        HttpResponse httpResponse;
                        // post请求
                        httpResponse = client.execute(httpPost);
                        HttpEntity httpEntity = httpResponse.getEntity();

                        if (httpEntity != null) {
                            response = EntityUtils.toString(httpEntity, "UTF-8");
                        }
                        client.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    ObjectMapper objectMapper = HibernateAwareObjectMapper.getInstance();
                    Map<String, String> statusMap = new HashMap<String, String>();
                    try {
                        statusMap = objectMapper.readValue(response, Map.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    if (!String.valueOf(statusMap.get("Code")).equals("10")) {
                        failMsg = failMsg + "获奖流水号：" + item.getId() + String.valueOf(statusMap.get("Msg")) + ";";
                    } else {
                        i++;
                    }
                } else {
                    failMsg = failMsg + "获奖流水号：" + item.getId() + "已经生产销售订单;";
                }

            }

        }
        if (StringUtils.isNotBlank(failMsg)) {
            setModel(OperationResult.buildFailureResult(failMsg));
        } else {
            setModel(OperationResult.buildSuccessResult("自动创建订单：" + i + "条记录"));
        }
        return buildDefaultHttpHeaders();
    }

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    @MetaData(value = "获奖明细")
    public HttpHeaders getLotteryWinDetails() {
        List<CbLotteryWinDetail> cbLotteryWinDetails = bindingEntity.getCbLotteryWinDetails();
        setModel(buildPageResultFromList(cbLotteryWinDetails));
        return buildDefaultHttpHeaders();
    }

    public HttpHeaders updateDelivery() {
        List<CbLotteryWin> cbLotteryWins = null;
        if (StringUtils.isNotBlank(getParameter("ids"))) {
            Long[] ids = this.getSelectSids();
            cbLotteryWins = cbLotteryWinService.findAll(ids);
        }
        Integer i = cbLotteryWinService.updateDelivery(cbLotteryWins);
        setModel(OperationResult.buildSuccessResult("更新成功:" + i + "条记录"));
        return buildDefaultHttpHeaders();
    }

}